package category

import (
	"context"
	constans "mall/services/product/rpc/consts"
	"mall/services/product/rpc/internal/domain/bo"
	"mall/services/product/rpc/internal/mapper"

	"mall/services/product/rpc/internal/svc"
	"mall/services/product/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type DelCategoryInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDelCategoryInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelCategoryInfoLogic {
	return &DelCategoryInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DelCategoryInfoLogic) DelCategoryInfo(in *pb.DelCategoryInfoDTO) (*pb.EmptyObj, error) {
	// get mapper
	categoryMapper := mapper.NewCategoryMapper(l.ctx)
	// 1.del self to db
	delSelfErr := categoryMapper.CategoryManage(l.svcCtx.DBEngin, in.CategoryIdArr, constans.Delete)
	if delSelfErr != nil {
		return nil, delSelfErr
	}
	// 2.del children  to loop
	loopDelErr := l.loopDelChildren(in.CategoryIdArr, categoryMapper)
	if loopDelErr != nil {
		return nil, loopDelErr
	}
	// 3.del children node arr
	return &pb.EmptyObj{}, nil
}

func (l *DelCategoryInfoLogic) loopDelChildren(categoryIdArr []int64, categoryMapper *mapper.CategoryMapper) error {
	categoryBO := bo.CategoryBO{ParentIdArr: categoryIdArr, NeStatus: constans.Delete}
	selectListCtx, err := categoryMapper.SelectListCtx(l.svcCtx.DBEngin, categoryBO)
	if err != nil {
		return err
	}
	for len(selectListCtx) < 1 {
		return nil
	}
	var childrenIdArr []int64
	for _, v := range selectListCtx {
		childrenIdArr = append(childrenIdArr, v.CategoryId)
	}
	loopDelErr := l.loopDelChildren(childrenIdArr, categoryMapper)
	if loopDelErr != nil {
		return loopDelErr
	}
	return nil
}
